package com.jq.view;

import com.jq.conf.Connection;
import com.jq.util.ConfUtil;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.stage.Stage;

import java.util.List;

public class StartConnectController {

    Stage stage;
    String url;
    private RootController rootController;

    @FXML
    private TableView<Connection> tableView;
    @FXML
    private TableColumn<Connection, String> firstColumn;
    @FXML
    private TableColumn<Connection, String> secondColumn;


    public void setStage(Stage stage) {
        this.stage = stage;
    }

    @FXML
    private void initialize() {

        initTableData();
        //设置单元格显示的值
        firstColumn.setCellValueFactory(cellData -> cellData.getValue().getNameProperty());
        secondColumn.setCellValueFactory(cellData -> cellData.getValue().getUrlProperty());


        tableView.getSelectionModel().selectedItemProperty().addListener(
                (observable, oldValue, newValue) -> {
                    if (newValue != null) {
                        this.url = newValue.getUrl();
                    } else {
                        this.url = null;
                    }

                });
    }

    //表格装载数据
    public void initTableData() {
        List<Connection> list = ConfUtil.load();
        ObservableList<Connection> data = FXCollections.observableArrayList(list);
        this.tableView.setItems(data);
    }

    public void connect() {
        rootController.setZkUrl(this.url);
        rootController.initZKData();
        this.stage.close();
    }

    public void setRootController(RootController rootController) {
        this.rootController = rootController;
    }

    public void removeConnection() {
        if (url != null) {
            List<Connection> list = ConfUtil.load();
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getUrl().equals(url)) {
                    list.remove(list.get(i));
                    break;
                }
            }
            if (list.size() > 0) {

                ConfUtil.overwrite(list);
            } else {
                ConfUtil.defeteFile();
            }
            initTableData();
        }

    }
}
